/**
 * Created by Administrator on 2016/7/1.
 */
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { NavBar, Drawer, ListView, Icon } from 'antd-mobile';
import { getHomeList, getThemes, getTheme, getNewsMore } from '../actions/home';
import { HomeList } from '../components/HomeList';
import '../assets/less/home.less';
import { Sidebar } from '../components/Sidebar';
import { agentImageURL } from '../utils';

const mapStateToProps = state => ({
  home: state.home
});

const mapDispatchTpProps = dispatch =>
  bindActionCreators(
    {
      getHomeList,
      getThemes,
      getTheme,
      getNewsMore
    },
    dispatch
  );

/**
 * connect中间件
 * connect一定要写在需要传递参数的组件头部，因为这是语法规则，只对当前关联的组件生效，和java的原理是一致的
 * state用法：state => state（传递全部state）
 * dispatch用法：（单个action）bindActionCreators(navActions, dispatch)，（多个action）bindActionCreators({...action1, ...action2}, dispatch)
 */
class NewsContainer extends React.Component {
  constructor(props) {
    super(props);
    //构造函数用法
    //常用来绑定自定义函数，切记不要在这里或者组件的任何位置setState，state全部在reducer初始化，相信对开发的后期很有帮助
    //例子：this.myfunction = this.myfunction.bind(this)
    // this.handleClick = this.handleClick.bind(this)
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2
    });
    this.state = {
      dataSource: dataSource.cloneWithRows({}),
      isLoading: false,
      open: false,
      storiesList: []
    };
    this.onOpenChange = this.onOpenChange.bind(this);
    this.onEndReached = this.onEndReached.bind(this);
  }

  onOpenChange = () => {
    this.setState({ open: !this.state.open });
  };

  async componentDidMount() {
    const id = this.props.match.params.id;
    await this.props.getTheme(id);
    await this.props.getThemes();
  }

  componentWillUpdate(nextProps, nextState) {
    // console.log(nextProps.match.params.id)
    // console.log(this.props.match.params.id)
    const id = nextProps.match.params.id;
    if (nextProps.match.params.id !== this.props.match.params.id) {
      this.props.getTheme(id);
    }
  }

  onEndReached = async event => {
    // load new data
    // hasMore: from backend data, indicates whether it is the last page, here is false
    // if (this.state.isLoading && !this.state.hasMore) {
    //     return;
    // }
    console.log('reach end', event);
    const id = this.props.match.params.id;
    this.setState({ isLoading: true });
    await this.props.getNewsMore(id, this.props.home.newsBefore);
    let data = [...this.state.storiesList, ...this.props.home.moreNews.stories];
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(data),
      isLoading: false,
      storiesList: data
    });
  };

  render() {
    const { theme, themes } = this.props.home;
    const { stories, name, image, description, editors } = theme;
    const row = (rowData, sectionID, rowID) => {
      return (
        <HomeList
          key={rowData.id}
          id={rowData.id}
          imgUrl={
            rowData.images && rowData.images[0] ? (
              agentImageURL(rowData.images[0])
            ) : (
              ''
            )
          }
          title={rowData.title}
        />
      );
    };
    return (
      <div className="home-wrapper">
        <NavBar iconName="ellipsis" mode="dark" onLeftClick={this.onOpenChange}>
          {name}
        </NavBar>
        <Drawer
          className="my-drawer"
          style={{ minHeight: document.documentElement.clientHeight - 45 }}
          contentStyle={{ color: '#A6A6A6', textAlign: 'center' }}
          sidebar={
            <Sidebar
              themes={themes}
              history={this.props.history}
              getTheme={() => this.props.getTheme()}
              onOpenChange={() => this.onOpenChange()}
            />
          }
          open={this.state.open}
          onOpenChange={this.onOpenChange}
        >
          {/*{JSON.stringify(theme.image)}*/}
          {// 轮播
          theme.image ? (
            <div
              className="carousel-item-wrap"
              style={{
                backgroundImage: 'url(' + agentImageURL(theme.image) + ')'
              }}
            >
              <div className="carousel-title">{description}</div>
            </div>
          ) : null}
          <div className="list-wrap">
            <div className="avatar-wrap">
              {editors ? <span>主编</span> : ''}
              {editors ? (
                editors.map((item, index) => {
                  return (
                    <i
                      key={index}
                      style={{
                        backgroundImage:
                          'url(' + agentImageURL(item.avatar) + ')'
                      }}
                    />
                  );
                })
              ) : (
                ''
              )}
            </div>
            {stories ? (
              stories.map(item => {
                return (
                  <HomeList
                    key={item.id}
                    id={item.id}
                    imgUrl={
                      item.images && item.images[0] ? (
                        agentImageURL(item.images[0])
                      ) : (
                        ''
                      )
                    }
                    title={item.title}
                  />
                );
              })
            ) : (
              ''
            )}
          </div>
          <ListView
            ref="lv"
            className="scroll-list-wrap"
            dataSource={this.state.dataSource}
            // renderHeader={() => <span>header</span>}
            renderFooter={() => (
              <div style={{ padding: 30, textAlign: 'center' }}>
                {this.state.isLoading ? <Icon type="loading" /> : null}
              </div>
            )}
            renderRow={row}
            // renderSeparator={separator}
            pageSize={10}
            useBodyScroll
            onScroll={() => {
              console.log('scroll');
            }}
            scrollRenderAheadDistance={500}
            scrollEventThrottle={200}
            onEndReached={this.onEndReached}
            onEndReachedThreshold={10}
          />
        </Drawer>
      </div>
    );
  }
}

export default connect(mapStateToProps, mapDispatchTpProps)(NewsContainer);

NewsContainer.propTypes = {
  home: PropTypes.object,
  match: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired
};
